package com.stylefeng.guns.modular.goods.service.impl;

import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.modular.goods.model.Spu;
import com.stylefeng.guns.modular.goods.dao.SpuMapper;
import com.stylefeng.guns.modular.goods.model.SpuSpec;
import com.stylefeng.guns.modular.goods.model.dto.SpuDto;
import com.stylefeng.guns.modular.goods.service.ISpuService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stylefeng.guns.modular.goods.service.ISpuSpecService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;

/**
 * <p>
 * spu表 服务实现类
 * </p>
 *
 * @author wuyifie
 * @since 2018-09-05
 */
@Service
public class SpuServiceImpl extends ServiceImpl<SpuMapper, Spu> implements ISpuService {
    @Autowired
    private ISpuSpecService spuSpecService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(SpuDto spuDto) {
        Spu spu = new Spu();
        BeanUtils.copyProperties(spuDto, spu);
        if (insert(spu)) {
            String ids = spuDto.getIds();
            if (!StringUtils.isEmpty(ids)) {
                for (String id : ids.split(",")) {
                    SpuSpec spuSpec = new SpuSpec();
                    spuSpec.setSpecId(Long.valueOf(id));
                    spuSpec.setSpuId(spu.getId());
                    spuSpecService.insert(spuSpec);
                }
            } else {
                throw new RuntimeException("没有选择规格信息");
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(Long spuId) {
        this.deleteById(spuId);
        spuSpecService.deleteByMap(Collections.singletonMap("spu_id", spuId));
    }
}
